package com.itwelkin.ssm.utils;


import com.itwelkin.ssm.model.Admin;
import com.itwelkin.ssm.system.SysException;
import org.junit.Test;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.UUID;

public class SystemUtils {

    private static DataSource dataSource;

    /**
     * 获取唯一字符串
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 得到参数加密后的MD5值
     */
    public static String getMD5(String inStr) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] inStrBytes = inStr.getBytes();
        try {
            MessageDigest MD = MessageDigest.getInstance("MD5");
            MD.update(inStrBytes);
            byte[] mdByte = MD.digest();
            char[] str = new char[mdByte.length * 2];
            int k = 0;
            for (int i = 0; i < mdByte.length; i++) {
                byte temp = mdByte[i];
                str[k++] = hexDigits[temp >>> 4 & 0xf];
                str[k++] = hexDigits[temp & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送邮件
     *
     * @param to   收件人
     * @param code 激活码
     */
    public static void sendMail(String to, String code) {
        // 1.属性对象
        Properties props = new Properties();
        props.setProperty("mail.smtp", "localhost");
        // 2.创建一个对象Session.
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("service@itwelkin.com", "123");
            }
        });
        // 3.创建一个代表邮件的对象:
        Message message = new MimeMessage(session);

        try {
            // 设置发件人:
            message.setFrom(new InternetAddress("service@itwelkin.com"));
            // 设置收件人:
            // TO:收件人.
            // CC:抄送
            // BCC:暗送,密送
            message.setRecipient(RecipientType.TO, new InternetAddress(to));
            // 设置邮件的主题:
            message.setSubject("客户管理系统帐户 -- 电子邮件激活确认");
            // 设置邮件的正文:
            message.setContent(
                    "<h1>欢迎来到客户管理系统</h1>" +
                            "<h3>尊敬的管理员您好！</h3>" +
                            "<h3>感谢您注册客户管理系统的管理员帐户。为激活您的帐户，请单击以下链接。</h3>" +
                            "<h3>" +
                            "<a href='" +
                            "http://localhost:8080//ssm_biao7/user/active?code=" + code + "'>" +
                            "http://localhost:8080//ssm_biao7/user/active?code=" + code + "" +
                            "</a>" +
                            "</h3>" +
                            "<h3>如果单击链接没有反应，请将链接复制到浏览器窗口中访问重试。</h3>" +
                            "<br/>" +
                            "<h3>致敬！</h3>" +
                            "<h3>zzz团队</h3>" +
                            "<h3>---------------------------------</h3>" +
                            "<h3>http://www.itwelkin.com</h3>",
                    "text/html;charset=UTF-8"
            );

            // 发送邮件:
            Transport.send(message);
            System.out.println("已向【" + to + "】邮箱帐户中成功发送激活邮件");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object checkVerify(HttpServletRequest request, String key, Object value){
        if (request.getSession().getAttribute("checkCode") == null
        || request.getParameter("checkCode") == null
        || request.getParameter("checkCode").trim().length() == 0
        || !request.getSession().getAttribute("checkCode").toString().equalsIgnoreCase(request.getParameter("checkCode"))){
            if (key != null){
                request.getSession().setAttribute(key,value);
            }
            request.getSession().setAttribute("msg","对不起您输入的验证码不正确");
            return null;
        }else {
            request.getSession().setAttribute("msg","");
        }

        return new Object();
    }

    public static boolean checkSession(HttpServletRequest request, HttpServletResponse response, boolean flag) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin adminUser = (Admin) session.getAttribute("adminUser");
        System.out.println(adminUser);
        if (adminUser == null){
            request.setAttribute("masg","请重新登录");
            request.getRequestDispatcher("/user/deng.jsp").forward(request,response);
            return true;
        }
        if (flag){
            if (!adminUser.getUsername().equalsIgnoreCase("admin")){
                session.removeAttribute("adminUser");
                request.setAttribute("masg","此功能只能是超级管理员使用");
                request.getRequestDispatcher("/user/deng.jsp").forward(request,response);
                return true;
            }
        }
        return false;
    }

    public static void checkOperation(HttpServletRequest request, HttpServletResponse response, SysException e) throws ServletException, IOException {
        //获取异常信息的提示
        request.setAttribute("msg",e.getMessage());
        //移除adminUser的用户信息
        request.getSession().removeAttribute("adminUser");
        //返回登录页面
        request.getRequestDispatcher("/user/deng.jsp").forward(request,response);
    }
}
